<template>
  <view class="container">
    <view class="step-wrap">
      <ve-steps :list="stepList" :active="activeStepListIndex" />
    </view>
    <view class="order-create-content" :style="{ 'padding-bottom': activeStepListIndex == 0 ? '130rpx' : '250rpx' }">
      <!-- 订单基础信息 -->
      <view class="basic-info" v-show="activeStepListIndex == 0">
        <ve-form :model="form" ref="formRef" :rules="rules">
          <customer orderShow="member" />
          <lease @timeRangeChange="timeRangeChange" />
          <platoon v-if="showPlatoonCard" />
        </ve-form>
      </view>
      <!-- 费用信息 -->
      <view class="order-fee-pane" v-show="activeStepListIndex == 1">
        <orderFeePane ref="orderFeePaneRef" />
      </view>
    </view>
    <footer-box id="footer-box">
      <block v-if="activeStepListIndex == 0">
        <ve-button size="long" :disabled="!nextStepIsValid" type="primary" @click="stepClickFn">下一步 去完善费用信息</ve-button>
      </block>
      <template #extra v-if="activeStepListIndex == 1">
        <feeStatistic />
      </template>
      <block v-if="activeStepListIndex == 1">
        <ve-button type="plain" @click="stepClickFn">上一步</ve-button>
        <ve-button type="primary" :loading="okLoading" @click="beforeSubmitFn">完成</ve-button>
      </block>
    </footer-box>

    <!-- 排车周期校验 -->
    <PlatoonCarCheckModal ref="platoonCarCheckModalRef" />
  </view>
</template>

<script setup name="ShortOrderForm">
  import { ref, provide, computed, nextTick, watch } from 'vue'
  // 组件
  import customer from '@/pages/order/components/customer/index.vue'
  import lease from './components/lease.vue'
  import platoon from './components/platoon.vue'
  import orderFeePane from './components/orderFeePane.vue'
  import footerBox from './components/footerBox.vue'
  import feeStatistic from '../components/order-fee/fee-statistic.vue'
  import PlatoonCarCheckModal from '@/components/confirm/platoon-car-check-modal.vue'
  // ---------------------------
  import { createOrderAPI, calcPriceAPI } from '@/api/order/sOrder'
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  import useFormFold from '@/hooks/useFormFold'
  import { cloneDeep } from '@/utils'
  import { timeRangeValidator } from './form-tool.js'
  import useToast from '@/hooks/useToast'
  import { userStore } from '@/stores'
  import { useOrderRedirectTo } from '@/hooks/useListNavigate'
  const userInfoStore = userStore()
  const epChannelOrderMaintenance = ref(1)
  userInfoStore.setEpDetail().then((response) => {
    epChannelOrderMaintenance.value = userInfoStore.epChannelOrderMaintenance
  })
  const dict = usePageDict('shortOrderDict')
  provide('dict', dict)

  // 表单规则
  const rules = computed(() => {
    let tempRules = {
      memberType: { required: true, message: '请选择客户类型' },
      memberPhone: [
        { required: true, message: '请输入联系电话' },
        { len: 11, match: /^[0-9]+$/, message: '仅支持数字，长度11位' },
      ],
      cardNumber: { match: /^[a-zA-Z0-9]+$/, message: '支持数字、英文' },
      emergencyContactPhone: { len: 11, match: /^[0-9]+$/, message: '请输入正确格式的紧急联系人手机号' },
      siteId: { required: true, message: '请选择取车门店' },
      orderSource: { required: true, message: '请选择订单来源' },
      timeRange: [{ required: true, message: '请选择预计租赁周期' }, { validator: timeRangeValidator }],
      // 承租人提示根据客户类型区分
      memberName: { required: true, message: form.value.memberType == 2 ? '请输入承租人' : '请选择承租人' },
    }
    // 客户类型为公司客户
    if (form.value.memberType == 1) {
      tempRules.clientId = { required: true, message: '请选择客户公司名称' }
    }
    // 渠道订单
    if (form.value.orderSource == 2) {
      tempRules.channelType = { required: true, message: '请选择订单渠道' }
      tempRules.channelOrderCode = { required: true, message: '请输入渠道单号' }
    }
    return tempRules
  })
  const { foldValidate } = useFormFold([])

  // 表单对象
  const defaultStartTime = dayjs().format('YYYY-MM-DD HH:mm:00')
  const form = ref({
    memberType: 2, // 客户类型
    cardType: 0, // 证件类型，默认身份证
    orderSource: 1, // 订单来源
    carSource: 1, // 车辆来源
    // 默认开始时间 开始
    timeRange: [defaultStartTime],
    startTime: defaultStartTime,
    // 默认开始时间 结束
    sendServiceFlag: 0,
    returnServiceFlag: 0,
  })
  provide('form', form)

  // 自动维护下不允许创建已排车订单，直接隐藏排车模块
  const showPlatoonCard = computed(() => {
    // 自动维护
    let isMaintenance = epChannelOrderMaintenance.value == 2
    let isChannelOrder = form.value.orderSource == 2
    if (isChannelOrder) {
      return isMaintenance
    }
    return true
  })
  // formRef
  const formRef = ref()

  // feeForm
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1, // 线下、线上费用需要根据选的是渠道订单还是线下订单处理
        feeDetailList: [],
        feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee', 'depositFee'],
      },
    ],
  })
  // 费用类型
  watch(
    () => form.value.orderSource,
    (newVal) => {
      let type = newVal == 1 ? 1 : 2
      feeForm.value.orderFee[0].feeType = type
      console.log(feeForm.value.orderFee[0].feeType)
    },
    { immediate: true },
  )
  provide('feeForm', feeForm)
  // 确认事件
  const orderFeePaneRef = ref()
  const okLoading = ref(false)
  const beforeSubmitFn = () => {
    // 获取费用信息，第二步
    orderFeePaneRef.value.getCostInfo((costInfo, priceModelId) => {
      let param = {
        ...form.value,
        ...costInfo,
        orderFee: {
          ...costInfo.orderFee[0],
          priceModelId,
        },
      }
      // 紧急联系人手机号格式校验
      if (form.value.emergencyContactPhone == '') {
        param.emergencyContactPhone = null
      }
      let beforeStatus = param.orderFee.feeDetailList.some((it) => {
        if (it.childrenList) {
          return it.childrenList.some((item) => {
            return item.amount === 0
          })
        } else {
          return it.amount === 0
        }
      })
      if (beforeStatus) {
        uni.showModal({
          title: '提示',
          content: '请注意，金额为0时不生成费项信息',
          success: function (res) {
            if (res.confirm) {
              submitFn(param)
            }
          },
        })
      } else {
        submitFn(param)
      }
    })
  }
  const submitFn = (param) => {
    okLoading.value = true
    createOrderAPI(param)
      .then((res) => {
        useToast({
          title: '创建成功',
        }).then(() => {
          useOrderRedirectTo('short-order')
        })
      })
      .catch(() => {
        okLoading.value = false
      })
  }
  // 下一步是否可点击
  const nextStepIsValid = computed(() => {
    // 需要判断必填项是否均填写
    let formValue = form.value
    let requiredProp = ['memberName', 'siteId', 'timeRange']
    // 个人客户
    if (formValue.memberType == 2) {
      requiredProp.push('memberPhone')
    }
    // 企业客户
    if (formValue.memberType == 1) {
      requiredProp.push('clientId')
    }
    // 渠道订单
    if (formValue.orderSource == 2) {
      requiredProp.push('channelType')
      requiredProp.push('channelOrderCode')
    }
    return !requiredProp.some((item) => {
      const value = formValue[item]
      if (item == 'timeRange') {
        // 时间范围：开始时间和结束时间需要都有值
        if (item && item.length) {
          if (value[0] && value[1]) {
            return !(value[0] && value[1])
          } else {
            return true
          }
        }
      } else {
        return !value
      }
    })
  })
  // form 聚焦部分字段是否发生变化
  const isChangeFormByProps = (propStrList, prevForm) => {
    let formVal = form.value
    return propStrList.some((prop) => formVal[prop] != prevForm[prop])
  }
  // 点击第二步、第一步事件
  // 步骤条数据
  // 读取门店模板配置，初始化 feeForm
  let prevForm = {}
  const stepList = ['订单信息', '费用信息']
  const activeStepListIndex = ref(0)
  const stepClickFn = () => {
    // 当前 step
    let currStep = activeStepListIndex.value
    // 切换到第二步
    if (currStep == 0) {
      // 第二步可以点击
      if (nextStepIsValid.value) {
        formRef.value.validate((valid, errors) => {
          if (!valid) {
            // 页面滚动到错误位置
            foldValidate(errors, true)
          } else {
            console.log('验证通过')
            let formValue = form.value
            if (
              isChangeFormByProps(
                [
                  'siteId',
                  'originalModelId',
                  'returnSiteId',
                  'startTime',
                  'endTime',
                  'sendServiceFlag',
                  'longitude',
                  'latitude',
                  'returnServiceFlag',
                  'returnLongitude',
                  'returnLatitude',
                ],
                prevForm,
              )
            ) {
              const param = {
                modelId: formValue.originalModelId,
                siteId: formValue.siteId,
                returnSiteId: formValue.returnSiteId,
                startTime: formValue.startTime,
                endTime: formValue.endTime,
                sendServiceFlag: formValue.sendServiceFlag ? 1 : 0,
                longitude: formValue.longitude,
                latitude: formValue.latitude,
                returnServiceFlag: formValue.returnServiceFlag ? 1 : 0,
                returnLongitude: formValue.returnLongitude,
                returnLatitude: formValue.returnLatitude,
                type: 1, // 固定值
              }
              calcPriceAPI(param).then((res) => {
                if (res.result) {
                  activeStepListIndex.value = 1
                  scrollToTopFn()
                  nextTick(() => {
                    orderFeePaneRef.value.initStoreTemplate(prevForm, res.result).then(() => {
                      prevForm = cloneDeep({
                        ...form.value,
                      })
                    })
                  })
                }
              })
            } else {
              activeStepListIndex.value = 1
              scrollToTopFn()
              nextTick(() => {
                orderFeePaneRef.value.initStoreTemplate(prevForm).then(() => {
                  prevForm = cloneDeep({
                    ...form.value,
                  })
                })
              })
            }
          }
        })
      }
    } else {
      activeStepListIndex.value = 0
      scrollToTopFn()
    }
  }

  // 页面滚动到顶部
  const scrollToTopFn = () => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 200,
    })
  }

  // 订单占用校验
  const platoonCarCheckModalRef = ref()
  const timeRangeChange = (val) => {
    platoonCarCheckModalRef.value.confirm({
      title: '请确认是否修改预计租赁周期？',
      params: {
        refId: form.value.id,
        startTime: val[0],
        endTime: val[1],
        useType: 2,
        carId: form.value.carId,
      },
      onCancel: () => {
        form.value.startTime = defaultStartTime
        form.value.endTime = undefined
        form.value.timeRange = [defaultStartTime]
        form.value.rentDays = undefined
      },
    })
  }
</script>

<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    background: #f7f8fa;
    .step-wrap {
      border-top: 1px solid #f7f8fa;
      background-color: #ffffff;
      box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0, 0, 0, 0.05);
      z-index: 9;
      position: fixed;
      width: 100%;
      left: 0;
    }
    .order-create-content {
      padding: 24rpx;
      padding-top: 178rpx;
      .basic-info {
        /deep/ .ve-card-content {
          padding-bottom: 0;
        }
      }
    }
    #footer-box {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      z-index: 999;
    }
  }
</style>
